<script setup lang="ts">
import { ElLoading, ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import LayoutTitle from '@/components/LayoutTitle/index.vue'
import ContentTitle from '@/components/ContentTitle/index.vue'
import Content from '@/components/Content/index.vue'
import { useAuth } from '@/stores/index'
import APICommon from '@/api/common'
import APIEnterPersonal from '@/api/enter-personal'
import APIInfoPersonal from '@/api/info-personal'
import type { setUserAuthData } from '@/api/info-personal/types'

const $router = useRouter()

const { info } = storeToRefs(useAuth())
const { getInfo } = useAuth()


const formData = ref<setUserAuthData>({
    type: 'company'
})

const refFrontSide = shallowRef<HTMLInputElement>()

function handleUploadFrontSide() {
    refFrontSide.value?.click()
}


/** 上传营业执照 */
function onUploadBusinessLicenseChange(e: Event) {
    const dom = (e.target as HTMLInputElement)
    if (!dom.files) return
    if (!['image/png', 'image/webp', 'image/jpeg', 'image/gif', 'image/bmp', 'image/svg+xml', 'image/x-icon'].includes(dom.files[0].type)) {
        dom.value = ''
        ElMessage.error('只能上传图片文件，请重新选择文件。')
        return
    }
    const fileSize = dom.files[0].size
    const fileSizeMB = fileSize / (1024 * 1024)
    if (fileSizeMB > 5) return ElMessage.error('上传文件大小不能超过5MB，请重新选择文件。')
    const loading = ElLoading.service({ lock: true })
    const form = new FormData()
    form.append('file', dom.files[0])
    APIEnterPersonal.companyOcr(form).then(({ data }) => {
        /** 真实姓名 */
        formData.value.real_name = data.ocr?.legal_representative?.value
        /** 营业执照 */
        formData.value.business_license = data.file
        /** 注册号 */
        formData.value.registration_code = data.ocr?.credit_code?.value
        /** 公司名 */
        formData.value.company_name = data.ocr?.name?.value
        /** 公司有效期 */
        formData.value.validity_period = data.ocr?.found_date?.value
        /** 公司地址 */
        formData.value.address = data.ocr?.address?.value
    }).finally(() => {
        /** 清除value，否者用户选择同一张图片，不会触发上传 */
        dom.value = ''
        loading.close()
    })
    // APIInfoPersonal.personalOcr(form).then(({ data }) => {
    //     formData.value.front_side = data.file
    //     formData.value.real_name = data.ocr.name
    //     formData.value.id_card = data.ocr.idno
    //     ElMessage.success('上传成功')
    // }).finally(() => {

    // })
}

const consent = shallowRef()
const formRef = shallowRef<FormInstance>()

function submitFormData() {
    if (!consent.value) return ElMessage.error('请勾选同意《心安元素信息认证协议》')
    formRef.value?.validate((valid: boolean) => {
        if (valid) {
            const loading = ElLoading.service({ lock: true })
            APIInfoPersonal.setUserAuth(formData.value).then(({ msg }) => {
                ElMessage.success(msg)
                getInfo()
                $router.replace({
                    name: 'Information'
                })
            }).finally(() => {
                loading.close()
            })
        }
    })
}

const rules = reactive({
    registration_code: [{ required: true, message: '请输入注册号', trigger: 'blur' }],
    company_name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
    real_name: [{ required: true, message: '请输入公司法人', trigger: 'blur' }],
    id_card: [{ required: true, message: '请输入法人身份证号', trigger: 'blur' }],
    validity_period: [{ required: true, message: '请输入公司有效期', trigger: 'blur' }],
    address: [{ required: true, message: '请输入公司地址', trigger: 'blur' }],
})

const isLongTerm = ref<boolean>(false)

watch(isLongTerm, (newValue) => {
    if (newValue) {
        formData.value.validity_period = '长期'
    } else {
        formData.value.validity_period = ''
    }
})

function handleJumpAgreement(type: string, mark: string) {
    window.open(`${import.meta.env.VITE_APP_WEB_URL}/agreement?type=${type}&mark=${mark}`, '_blank')
}

</script>

<template>
    <div class="authentication">
        <el-form :model="formData" ref="formRef" label-width="auto" :rules="rules">
            <LayoutTitle class="nav" title="公司-店铺入驻信息" />
            <Content class="center">
                <ContentTitle title="账号基本信息：" />
                <div class="info">
                    <div class="con">
                        <div class="label">用户名：</div>
                        <div class="value">{{ info.username }}</div>
                    </div>
                    <div class="con">
                        <div class="label">账号ID：</div>
                        <div class="value">{{ info.Invite_code }}</div>
                    </div>
                </div>
            </Content>
            <Content class="center">
                <ContentTitle title="上传身份信息：" />
                <div class="upload-info">
                    <div class="left">
                        <div @click="handleUploadFrontSide" class="front">
                            <img v-if="formData.business_license" :src="formData.business_license" alt="营业执照">
                            <div v-else class="upload-text">
                                <div>+</div>
                                <div>营业执照</div>
                            </div>
                        </div>
                        <input ref="refFrontSide" type="file" @change="onUploadBusinessLicenseChange"
                            style="display: none;" accept="image/*">
                        <div class="notice">注意：上传小于5MB大小的jpg/jpeg图片；</div>
                        <div class="QR-code">
                            <div></div>
                            <p>或手机扫描上传营业执照</p>
                        </div>
                    </div>
                    <div class="right">
                        <el-form-item label="注册号：" prop="registration_code">
                            <el-input v-model="formData.registration_code" placeholder="请输入注册号" />
                        </el-form-item>
                        <el-form-item label="公司名称：" prop="company_name">
                            <el-input v-model="formData.company_name" placeholder="请输入公司名称" />
                        </el-form-item>
                        <el-form-item label="公司法人：" prop="real_name">
                            <el-input v-model="formData.real_name" placeholder="请输入公司法人" />
                        </el-form-item>
                        <el-form-item label="法人身份证号：" prop="id_card">
                            <el-input v-model="formData.id_card" placeholder="请输入法人身份证号" />
                        </el-form-item>
                        <el-form-item label="公司有效期：" style="display: flex;" prop="validity_period">
                            <el-input v-model="formData.validity_period" placeholder="请输入公司有效期" style="width: 305px;" />
                            <el-checkbox v-model="isLongTerm" label="长期" size="large" style="margin-left: 20px;" />
                        </el-form-item>
                        <el-form-item label="公司地址：" prop="address">
                            <el-input v-model="formData.address" placeholder="请输入公司地址" />
                        </el-form-item>
                    </div>
                </div>
            </Content>
            <div class="bottom">
                <div>
                    <el-checkbox v-model="consent" size="large">
                        同意
                    </el-checkbox>
                    <span class="agreement" @click="handleJumpAgreement('register', 'auth')">《心安元素信息认证协议》</span>
                </div>
                <button type="button" @click="submitFormData">提交认证信息</button>
            </div>
        </el-form>
    </div>
</template>

<style lang="scss">
.authentication {
    .bottom {
        width: 75%;
        margin: 0 auto;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 20px 0;
        margin-bottom: 50px;

        button {
            width: 230px;
            height: 40px;
            border-radius: 5px;
            background-color: rgba(15, 64, 245, 1);
            color: rgba(255, 255, 255, 1);
            font-size: 14px;
            border: none;
            cursor: pointer;
        }

        div {
            display: flex;
            align-items: center;

            .agreement {
                cursor: pointer;
                line-height: 1em;
                color: #1684FC;
                font-size: 14px;
            }
        }
    }

    .center {
        width: 75%;
        margin: 0 auto;
        margin-bottom: 30px;

        .signature-sale {
            padding: 20px;

            .explain {
                display: flex;
                gap: 0 15px;
                margin-top: 15px;

                p {
                    font-size: 14px;

                    &:last-child {
                        color: rgba(154, 154, 154, 1);
                    }

                    &:first-child {
                        color: rgba(107, 173, 247, 1);
                    }
                }
            }

            .con {
                display: flex;
                align-items: center;
                gap: 0 35px;

                .is-upload-copyright {
                    color: #67C23A;
                }

                .value {
                    width: 190px;
                    height: 35px;
                    border-radius: 5px;
                    background-color: rgba(255, 255, 255, 1);
                    color: #1684FC;
                    font-size: 14px;
                    border: 1px dashed rgba(22, 132, 252, 1);
                    cursor: pointer;
                }

                .label {
                    color: rgba(16, 16, 16, 1);
                    font-size: 14px;
                }
            }
        }

        .upload-info {
            display: flex;
            justify-content: space-between;
            padding: 30px 45px;

            .right {
                width: 500px;
            }

            .left {
                .notice {
                    color: rgba(190, 190, 190, 1);
                    font-size: 14px;
                    margin-top: 14px;
                }

                .QR-code {
                    display: flex;
                    align-items: flex-end;
                    margin-top: 32px;
                    margin-bottom: 56px;

                    div {
                        width: 115px;
                        height: 115px;
                        background-color: #eeeeee;
                    }

                    p {
                        color: rgba(16, 16, 16, 1);
                        font-size: 14px;
                        margin-left: 18px;
                    }
                }

                .front {
                    background-image: url('./images/business-license.png');
                    background-size: 100% 100%;
                }

                .front {
                    width: 220px;
                    height: 140px;
                    margin-top: 20px;
                    cursor: pointer;

                    img {
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                    }
                }

            }
        }

        .info {
            display: flex;
            margin: 30px 0;
            padding: 0 50px;

            .con {
                display: flex;
                align-items: center;
                flex: 1;

                .value {
                    color: rgba(154, 154, 154, 1);
                    font-size: 14px;
                }

                .label {
                    color: rgba(16, 16, 16, 1);
                    font-size: 15px;
                }
            }
        }
    }

    .nav {
        margin-bottom: 20px;
    }
}
</style>
